#include "InputHandler.h"
#include "DummyTracker.h"
#include "GameHandler.h"
#include "Player.h"


GameHandler* GameHandler::s_pInstance = nullptr; 


bool GameHandler::Init(std::string title, int xPos, int yPos, int height, int width, int flags)
{
	if (SDL_Init(SDL_INIT_EVERYTHING) >= 0) 
	{
		m_window.Init(title.c_str(), xPos, yPos, height, width, flags); 
		m_renderer.Init(m_window);
		TextureManager::Instance() -> loadTexture("assets/animate-alpha.png", "Animate", m_renderer.m_pRenderer); 
		m_gameObjects.push_back(new Player(new Loader(100, 100, 128, 82, "Animate")));
		//m_gameObjects.push_back(new Enemy(new Loader(300, 300, 128, 82, "Animate"))); 
		//m_gameObjects.push_back(new Enemy(new Loader(0, 0, 128, 82, "Animate"))); 
		m_gameObjects.push_back(new DummyTracker(new Loader(0, 0, 128, 82, "Animate"))); 
		InputHandler::Instance() -> initJoy(); 	
		m_bRunning = true; 
		return true;
	}

	return false; 
}


void GameHandler::Render()
{
	// Clear the renderer
	SDL_RenderClear(m_renderer.m_pRenderer);
	// Set the default renderer color 
	SDL_SetRenderDrawColor(m_renderer.m_pRenderer, 255, 0, 0, 255); 
	
	for (std::vector <GameObject*>::size_type i = 0; i != m_gameObjects.size(); ++i)
		m_gameObjects[i] -> Render(); 

	// Render the window to the screen
	SDL_RenderPresent(m_renderer.m_pRenderer); 
}


void GameHandler::Update()
{
	for (std::vector <GameObject*>::size_type i = 0; i != m_gameObjects.size(); ++i)
		m_gameObjects[i] -> Update(); 

	DummyTracker* dt = dynamic_cast <DummyTracker*> (m_gameObjects[1]);
	Player* p        = dynamic_cast <Player*> (m_gameObjects[0]); 

	dt -> Track(*p); 
}


void GameHandler::handleEvents()
{
    InputHandler::Instance() -> Update(); 
}


void GameHandler::CleanUp()
{
	for (std::vector <GameObject*>::size_type i = 0; i != m_gameObjects.size(); ++i)
		delete m_gameObjects[i]; 

	InputHandler::Instance() -> CleanUp(); 
	
	SDL_Quit();
}


